<template>
  <publish-sucess-heade />
  <div class="post-creator">
    <div class="header">
      <h1>{{ isEditMode ? '编辑文章' : '创作中心' }}</h1>
      <p>创作您的精彩内容，与世界分享您的见解</p>
    </div>

    <div class="editor-container">
      <div class="form-group">
        <label for="title">标题</label>
        <input type="text" id="title" v-model="post.title" placeholder="输入标题..." class="title-input">
      </div>

      <div class="form-group">
        <label for="remark">简介</label>
        <textarea id="remark" v-model="post.remark" placeholder="输入简介..." rows="3" class="remark-textarea"></textarea>
      </div>
      <div class="form-group">
          <label>标签</label>
          <div class="tag-editor">
            <el-input-tag v-model="post.tags" :max="3"  clearable placeholder="请输入标签，最多输入三个标签" 
            style="padding: 10px;"/>
            <!-- 输入框用于新增标签 -->
            <!-- <el-input v-model="newTag" placeholder="输入新标签" @keyup.enter="addTag"
              style="width: 200px; margin-bottom: 10px;" />
            <el-button @click="addTag" type="primary" plain size="small">添加</el-button> -->

            <!-- 已选标签列表（支持拖拽） -->
            <!-- <draggable v-model="post.tags" tag="div" class="selected-tags" v-if="post.tags">
              <el-tag v-for="(tag, index) in post.tags" :key="index" closable @close="removeTag(index)"
                style="margin: 5px; cursor: move;">
                {{ tag }}
              </el-tag>
            </draggable> -->

            <!-- 热门推荐标签 -->
            <!-- <div class="popular-tags">
              <strong>热门标签:</strong>
              <el-tag v-for="tag in popularTags" :key="tag" @click="addPopularTag(tag)"
                style="margin: 5px; cursor: pointer;">
                {{ tag }}
              </el-tag>
            </div> -->
          </div>
        </div>


      <div class="form-group">
        <label>内容</label> 



        <!-- Vditor 编辑器容器 -->
        <div class="vditor-wrapper" v-loading="isLoading">
          <div class="editor-toolbar">
            <div class="mode-toggle">
              <button @click="setMode('wysiwyg')" :class="{ active: editorMode === 'wysiwyg' }">可视化</button>
              <button @click="setMode('ir')" :class="{ active: editorMode === 'ir' }">即时渲染</button>
              <button @click="setMode('sv')" :class="{ active: editorMode === 'sv' }">分屏编辑</button>
              <button @click="showPreview = !showPreview" :class="{ active: showPreview }">预览</button>
            </div>
            <div class="word-count">
              <span>字数: {{ wordCount }}</span>
            </div>
          </div>
          <div id="vditor" class="vditor" :class="{ hidden: isLoading }"></div>
        </div>
      </div>

      <div class="actions">
        <button class="save-draft" @click="saveDraft">保存草稿</button>
        <button class="publish" @click="handleSubmit">
          {{ isEditMode ? '更新帖子' : '发布帖子' }}
        </button>
      </div>
    </div>

    <div class="preview-section" v-if="showPreview">
      <h2>预览效果</h2>
      <div class="preview-container">
        <div class="preview-title">{{ post.title || '标题预览' }}</div>
        <div class="preview-remark">{{ post.remark || '简介预览' }}</div>
        <div class="preview-content" v-html="previewContent"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import messagePost from '@/utils/message.js'
import PublishSucessHeade from '@/components/PublishSucessHeade.vue'
import {createArticle ,getArticleByArticleId,updateArticle } from '../api/articlesApi.js'

const route = useRoute()
const router = useRouter()

// 判断是否为编辑模式
const isEditMode = ref(!!route.params.id)
const articleId = ref(route.params.id)

// 表单数据
const post = reactive({
  title: '',
  remark: '',
  content: '# 欢迎使用 Vditor\n\n在这里创作您的精彩内容...',
  tags:  [],
  oldTags: [],
})

const editorMode = ref('wysiwyg')
const showPreview = ref(false)
const previewContent = ref('')
const wordCount = ref(0)
let vditor = null
const isLoading = ref(true)
onMounted(async () => {
  // 如果是编辑模式，加载文章数据
  if (isEditMode.value) {
    const data = await getArticleByArticleId(articleId.value)
    if (data) {
      // console.log(data);
      
      post.title = data.title
      post.remark = data.remark
      post.content = data.content
      post.tags = data.tags
      post.oldTags = data.tags
    } else {
      messagePost({ message: '加载文章失败', type: 'error' })
      router.push('/manage-posts')
      return
    }
  }


  vditor = new Vditor('vditor', {
    value: post.content,
    mode: getVditorMode(),
    height: 500,
    toolbarConfig: { pin: true },
    cache: { enable: false },
    input: (value) => {
      post.content = value
      wordCount.value = value.length
      previewContent.value = vditor.getHTML()
    },
    after: () => {
      isLoading.value = false
      previewContent.value = vditor.getHTML()
    }
  })
})

function getVditorMode() {
  switch (editorMode.value) {
    case 'wysiwyg': return 'wysiwyg'
    case 'ir': return 'ir'
    case 'sv': return 'sv'
    default: return 'wysiwyg'
  }
}

function setMode(mode) {
  editorMode.value = mode
  if (!vditor) {
    console.warn('Vditor 尚未初始化')
    return
  }
  try {
    vditor.setMode(mode)
  } catch (e) {
    console.error('切换编辑器模式失败:', e)
  }
}

function saveDraft() {
  localStorage.setItem('postDraft', JSON.stringify(post))
  messagePost({
    message: "草稿已保存！",
    type: 'success',
  })
}

async function handleSubmit() {
  if (!post.title.trim()) {
    messagePost({ message: "请输入标题", type: 'error' })
    return
  }

  if (!post.content.trim()) {
    messagePost({ message: "内容不能为空", type: 'error' })
    return
  }

  if (!post.remark.trim()) {
    messagePost({ message: "请输入简介", type: 'error' })
    return
  }
  console.log('post:', post);
  

  try {
    let response
    if (isEditMode.value) {
      // 更新文章
      post.id = articleId.value
      console.log('post:', post);
      
      response = await updateArticle(post)
      messagePost({ message: "文章更新成功", type: 'success' })
    } else {
      // 创建文章
      response = await createArticle(post)
      messagePost({ message: "帖子发布成功", type: 'success' })
      articleId.value = response
      isEditMode.value = true
    }

    // 跳转到成功页面
    router.push(`/publishSuccess/${articleId.value}`)

  } catch (error) {
    messagePost({ message: "操作失败，请重试", type: 'error' })
    console.error('请求失败:', error)
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Noto Sans SC', sans-serif;
}

body {
  background-color: #f5f7fa;
  color: #333;
  padding: 20px;
}

.post-creator {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.header h1 {
  font-size: 2.2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.header p {
  font-size: 1.1rem;
  color: #7f8c8d;
}

.editor-container {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  font-weight: 500;
  margin-bottom: 8px;
  color: #2c3e50;
  font-size: 1rem;
}

.title-input,
.remark-textarea {
  width: 100%;
  padding: 14px;
  border: 1px solid #e0e6ed;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s;
}

.title-input {
  font-size: 1.4rem;
  font-weight: 700;
}

.title-input:focus,
.remark-textarea:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.mode-toggle {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background 0.3s;
}

.mode-toggle:hover {
  background: #2980b9;
}

.word-count {
  color: #7f8c8d;
  font-size: 0.9rem;
}

.vditor {
  border: 1px solid #e0e6ed;
  border-radius: 8px;
  overflow: hidden;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
}

.save-draft,
.publish {
  padding: 12px 25px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.save-draft {
  background: #f1f2f6;
  color: #2c3e50;
}

.save-draft:hover {
  background: #dfe4ea;
}

.publish {
  background: #2ecc71;
  color: white;
}

.publish:hover {
  background: #27ae60;
}

.preview-section {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
}

.preview-section h2 {
  font-size: 1.6rem;
  color: #2c3e50;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.preview-container {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.preview-title {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 15px;
  color: #2c3e50;
}

.preview-remark {
  font-size: 1.1rem;
  color: #7f8c8d;
  margin-bottom: 25px;
  line-height: 1.6;
}

.preview-content {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.vditor-wrapper {
  position: relative;
  width: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  border-radius: 8px;
}

.loading-text {
  font-size: 14px;
  color: #666;
  /* 可以替换为 loading 图标 */
}

.vditor.hidden {
  visibility: hidden;
}
</style>